﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Web.Services.Protocols;

namespace Axial
{
	public static partial class CallHandler
	{
		[CallHandler(typeof(Extensions))]
		private static string HandleExtensionsJSCall(MethodInfo method, object called, object[] stack)
		{
			if (method.Name == "JSCall")
			{
				SoapHttpClientProtocol proxy = (SoapHttpClientProtocol)stack[0];
				string methodName = ((string)stack[1]).RemoveOuterCharacters();
				MethodInfo serviceMethod = proxy.GetType().GetMethod(methodName);
				Action<object> successCallback = (Action<object>)stack[2];
				Action<object> failureCallback = (Action<object>)stack[3];

				if (serviceMethod == null)
					throw new Exception("The web service method does not exist.");

				// create js object to pass as params
				ParameterInfo[] parameters = serviceMethod.GetParameters();
				string paramNameArray = "[]";
				if (parameters.Length > 0)
					paramNameArray = "['" + String.Join("','", parameters.Select(pi => pi.Name).ToArray()) + "']";
				return string.Format("Axial.CallScriptService('{0}', '{1}', Axial.ArrayToObject({5}, {2}), {3}, {4})",
					proxy.Url, serviceMethod.Name, stack[4], successCallback.Method.Name, failureCallback.Method.Name, paramNameArray);
			}
			return null;
		}
	}
}
